package com.imooc.sell.converter;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.imooc.sell.dataobject.OrderDetail;
import com.imooc.sell.dto.OrderDTO;
import com.imooc.sell.enmus.ResultEnum;
import com.imooc.sell.exception.SellException;
import com.imooc.sell.form.OrderForm;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * Description:
 * 转换
 *
 * @author zzy
 * @create 2017-09-13 08:06
 */
@Slf4j
public class OrderForm2OrderDOTConverter {
    public static OrderDTO convert(OrderForm orderForm) {
        Gson gson
                = new Gson();


        OrderDTO orderDTO = new OrderDTO();
        orderDTO.setBuyerName(orderForm.getName());
        orderDTO.setBuyerPhone(orderForm.getPhone());
        orderDTO.setBuyerAddress(orderForm.getAddress());
        orderDTO.setBuyerOpenid(orderForm.getOpenid());

        List<OrderDetail> orderDetails = new ArrayList<>();
        try {
            orderDetails = gson.fromJson(orderForm.getItems(), new TypeToken<List<OrderDetail>>() {
            }.getType());
        } catch (Exception e) {
            log.error("【对象转化】错误,String ={}", orderForm.getItems());
            throw new SellException(ResultEnum.PARAM_ERROR);
        }

        //取到一个string
        orderDTO.setOrderDetailList(orderDetails);

        return orderDTO;

    }
}